<template>
  <div class="search">
    <van-nav-bar
      title="搜索中心"
      left-arrow
      @click-left="$router.back()"
    ></van-nav-bar>

    <!-- 搜索框 -->
    <van-search
      v-model.trim="value"
      show-action
      shape="round"
      placeholder="请输入搜索关键词"
      @input="inputFn"
    >
      <template #action>
        <div @click="onSearch(value)">搜索</div>
      </template>
    </van-search>

    <!-- 推荐 -->
    <van-cell-group v-if="value">
      <van-cell
        @click="onSearch(item)"
        icon="search"
        v-for="(item, index) in sugList"
        :key="index"
      >
        <span v-html="Lihigt(item)"></span>
      </van-cell>
    </van-cell-group>

    <!-- 历史记录 -->
    <van-cell-group v-else>
      <van-cell title="历史记录"></van-cell>
      <van-cell
        :title="item"
        v-for="item in history"
        :key="item"
        @click="onSearch(item)"
      >
        <van-icon name="close" @click.stop="del(item)" />
      </van-cell>
    </van-cell-group>
    <van-empty
      image="search"
      description="目前暂时没有您想要的"
      v-show="value && sugList.length === 0"
    />
  </div>
</template>

<script>
import { getSuggest } from '@/api/search'
import {
  setStroageSearchHistory,
  getStroageSearchHistory
} from '@/utils/storage'
export default {
  name: 'Search',
  data() {
    return {
      value: '',
      sugList: [],
      history: getStroageSearchHistory()
    }
  },
  methods: {
    onSearch(item) {
      if (item.length === 0) {
        return
      }
      if (this.history) {
        this.history = this.history.filter((content) => content !== item)
      }
      // 在添加
      this.history.unshift(item)
      setStroageSearchHistory(this.history)

      this.$router.push({
        path: '/result',
        query: {
          keyword: item
        }
      })
    },

    del(item) {
      // 删除历史记录
      this.history = this.history.filter((content) => content !== item)

      // 存到本地
      setStroageSearchHistory(this.history)
    },
    async inputFn(val) {
      // 关闭定时器，防抖
      clearTimeout(this.timeId)
      this.timeId = setTimeout(async () => {
        if (val.length === 0) return
        const res = await getSuggest(val)
        // 当没有数据时,sugList数组为空
        if (res.data.options[0] === null) {
          return (this.sugList = [])
        }
        this.sugList = res.data.options
      }, 500)
    },
    // 处理高亮
    Lihigt(item) {
      const res = new RegExp(this.value, 'gi')
      return item.replace(res, function (content) {
        return `<span style="color:red">${content}</span>`
      })
    }
  }
}
</script>

<style></style>
